package com.litchi.tutor.common.util;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Pattern;

/**
 * @author hoby
 * @since 2021-08-19
 */
@Slf4j
public class IpUtil {

    /**
     * 获取访问用户的客户端IP（适用于公网与局域网）
     */
    public static String getIpAddr(HttpServletRequest request) {
        try {
            if (request == null) {
                return "null";
            }
            String ipString = request.getHeader("X-Forwarded-For");
            if (StringUtils.isEmpty(ipString) || "unknown".equalsIgnoreCase(ipString)) {
                ipString = request.getHeader("Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ipString) || "unknown".equalsIgnoreCase(ipString)) {
                ipString = request.getHeader("WL-Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ipString) || "unknown".equalsIgnoreCase(ipString)) {
                ipString = request.getHeader("HTTP_CLIENT_IP");
            }
            if (StringUtils.isEmpty(ipString) || "unknown".equalsIgnoreCase(ipString)) {
                ipString = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (StringUtils.isEmpty(ipString) || "unknown".equalsIgnoreCase(ipString)) {
                ipString = request.getHeader("X-Real-IP");
            }
            if (StringUtils.isEmpty(ipString) || "unknown".equalsIgnoreCase(ipString)) {
                ipString = request.getRemoteAddr();
            }
            // 多个路由时，取第一个非unknown的ip
            String[] arr = ipString.split(",");
            for (String str : arr) {
                if (!"unknown".equalsIgnoreCase(str)) {
                    ipString = str;
                    break;
                }
            }
            return "0:0:0:0:0:0:0:1".equals(ipString) ? "127.0.0.1" : ipString;
        } catch (Exception e) {
            return "null";
        }
    }

    public static boolean isInternalIp(HttpServletRequest request) {
        return isInternalIp(getIpAddr(request));
    }

    /**
     * 判断是否内网ip
     *
     * @param ip 需要匹配的ip
     * @return
     */
    public static boolean isInternalIp(String ip) {
        if (StrUtil.isEmpty(ip)) {
            return false;
        }
        String reg = "^(127\\.0\\.0\\.1)|(localhost)|(10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})|(172\\.((1[6-9])|(2\\d)|(3[01]))\\.\\d{1,3}\\.\\d{1,3})|(192\\.168\\.\\d{1,3}\\.\\d{1,3})$";
        boolean matches = Pattern.matches(reg, ip.trim());
        return matches;
    }

}
